<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="pdfFileName">
        <el-input
          v-model="queryParams.pdfFileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:file:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['system:file:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="indexMethod" align="center"/>
      <el-table-column label="查看文件" align="center">
        <template #default="scope">
          <span v-if="!scope.row.pdfUrl">无文件</span>
          <el-button v-else type="text" @click="openPdfPreview(scope.row.pdfUrl)">
            <span style="font-size: 16px; color: #409EFF; word-break: break-all;">{{ scope.row.pdfFileName }}...</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleLoad(scope.row)" v-hasPermi="['system:file:edit']">下载</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:file:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- PDF预览弹窗 -->
    <el-dialog   title="在线预览" :visible.sync="dialogVisible"   width="60%"  top="30px"  @close="closePdfPreview">
      <div v-if="currentPdfUrl" class="pdf-container">
        <!-- PDF预览组件 -->
        <div class="pdf-viewer">
          <pdf
            :src="currentPdfUrl"
            :page="currentPage"
            :scale="scale"
            @num-pages="totalPages = $event"
            @page-loaded="currentPage = $event">
          </pdf>
        </div>
      </div>
      <div v-else style="text-align: center; padding: 50px;">
        加载中...
      </div>

      <!-- 分页和缩放控制 -->
      <div class="pdf-controls" v-if="currentPdfUrl">
        <div class="control-group">
          <el-button type="text" @click="goToFirstPage" :disabled="currentPage === 1">
            首页
          </el-button>
          <el-button type="text" @click="goToPreviousPage" :disabled="currentPage === 1">
            上一页
          </el-button>
          <span class="page-info">
      {{ currentPage }} / {{ totalPages }}
    </span>
          <el-button type="text" @click="goToNextPage" :disabled="currentPage === totalPages">
            下一页
          </el-button>
          <el-button type="text" @click="goToLastPage" :disabled="currentPage === totalPages">
            末页
          </el-button>
        </div>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import { listFile, delFile } from "@/api/system/file";
import pdf from 'vue-pdf';
import Pagination from "@/components/Pagination";

export default {
  name: "File",
  components: {
    pdf,
    Pagination
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成绩pdf管理表格数据
      fileList: [],
      // 时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pdfFileName: null,
        pdfUrl: null,
        createTime: null,
      },
      // PDF预览相关状态
      dialogVisible: false,
      currentPdfUrl: '',
      currentPage: 1,
      totalPages: 0,
      scale: 1.0 // PDF缩放比例
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询成绩pdf管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 打开PDF预览弹窗 */
    openPdfPreview(pdfUrl) {
      // 重置状态
      this.resetPdfPreview();
      this.currentPdfUrl = pdfUrl;
      this.currentPage = 1;
      this.dialogVisible = true;
    },
    /** 重置PDF预览状态 */
    resetPdfPreview() {
      this.currentPdfUrl = '';
      this.currentPage = 1;
      this.totalPages = 0;
      this.scale = 1.0;
    },
    /** 关闭PDF预览弹窗 */
    closePdfPreview() {
      this.dialogVisible = false;
      // 延迟重置状态
      this.$nextTick(() => {
        setTimeout(() => {
          this.resetPdfPreview();
        }, 300);
      });
    },
    /** 调整PDF缩放 */
    goToFirstPage() {
      this.currentPage = 1;
      this.scrollToTop();
    },

    goToPreviousPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.scrollToTop();
      }
    },

    goToNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.scrollToTop();
      }
    },

    goToLastPage() {
      this.currentPage = this.totalPages;
      this.scrollToTop();
    },

    scrollToTop() {
      this.$nextTick(() => {
        const pdfContainer = document.querySelector('.pdf-container');
        if (pdfContainer) {
          pdfContainer.scrollTop = 0;
        }
        // 滚动整个对话框到顶部
        const dialog = document.querySelector('.el-dialog__body');
        if (dialog) {
          dialog.scrollTop = 0;
        }
      });
    },
    /** 下载文件 */
    handleLoad(row) {
      fetch(row.pdfUrl)
        .then(response => response.blob())
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          const fileName = row.pdfFileName ? row.pdfFileName.substring(row.pdfFileName.lastIndexOf('/') + 1) : 'file.pdf';
          link.download = fileName;
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        })
        .catch(error => {
          this.$modal.msgError("下载失败");
          console.error('下载失败:', error);
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除成绩pdf管理编号为"' + ids + '"的数据项？').then(function() {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 序号计算方法
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


<style scoped>
/* 可以添加一些自定义样式 */
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.pdf-container {
  height: 75vh; /* 增加容器高度 */
  overflow: auto;
  background-color: #f5f5f5;
  padding: 20px; /* 保持适当内边距 */
  text-align: center;
}

.pdf-viewer {
  margin-top: -50px;
  display: inline-block;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background: white;

  max-width: 70%;
  width: 80%; /* 设置固定宽度比例 */
}

/* 控制按钮样式 - 居中对齐 */
.pdf-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
  padding: 10px 0;
  border-top: 1px solid #eee;
  width: 100%;
}
</style>
